package com.gopay.checkorder.service.impl.expay;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.common.util.DateUtils;
import com.gopay.checkorder.manager.BankOrderManager;
import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.PabConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.pab.expay.PabExPayMessage;
import com.gopay.common.domain.bank.pab.expay.res.PabExPayFastpaySOQResFather;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.remote.bank.BankInteractRemoteService;
import com.gopay.remote.bank.ExPayInteractRemoteService;

/**
 * 平安快捷支付结果查询
 * @author ShenJun
 *
 */
public class CheckOrderPabExPayImpl implements BankOrderService {

    private final static Logger logger = LoggerFactory.getLogger("PAB");

    @Resource(name = "bankExPayClient")
    private ExPayInteractRemoteService bankExPayClient;
    
    @Resource(name = "bankClient")
    private BankInteractRemoteService bankClient;
    
   @Override
   public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
	   logger.error("CheckOrderPabExPayImpl处理BankOrder对象:" + ToStringBuilder.reflectionToString(bankOrder) );
       CheckOrderResult checkOrderResult = new CheckOrderResult();
       checkOrderResult.setSuccess(false);
       checkOrderResult.setOrderId(bankOrder.getOrderId());

       PabExPayMessage base = new PabExPayMessage();
       base.setOrderId(bankOrder.getOrderId());
       base.setBankOrderId(bankOrder.getOutOrderId());
       base.setBank(BankConstants.BANK_LOGO_PAB);
       base.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
       base.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
       
       Result result = new Result();
       try {
    	   	if(BisBankBusinessProd._12.value.equals(bankOrder.getBankBizProdCode())){
				base.setTkOriBankOrderId(bankOrder.getOriOutOrderId());
			}
   			if(BisBankBusinessProd._12.value.equals(bankOrder.getBankBizProdCode())
   				&& DateUtils.isToday(bankOrder.getSendBankTm())){
   				//如果是当日的退款订单，就直接返回处理中状态
   				logger.error("平安EXPAY订单" + bankOrder.getOrderId() + "为当日的退款订单，只有次日才能查询到订单，此时返回处理中状态");
                checkOrderResult.setErrMsg("当日退款订单，银行返回处理中");
   			} 
   			else{
   				//不是当日的退款订单，就调对账接口
   				result = bankExPayClient.queryOrder(base);
   	           if (result == null || !result.isSuccess()) {
   	               logger.error("bankClient fail.");
   	               if(result ==null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())){
   	                   BankCountDownLatch.failIncrease(bankOrder.getBankCode());
   	               }
   	               logger.error(ToStringBuilder.reflectionToString(result,ToStringStyle.DEFAULT_STYLE));
   	               checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
   	               checkOrderResult.setErrMsg("系统返回对账结果为空");
   	               return checkOrderResult;
   	           }
   	           logger.error("平安EXPAY订单" + bankOrder.getOrderId() + "查询结果："+ result.isSuccess());
   	           PabExPayFastpaySOQResFather res = (PabExPayFastpaySOQResFather) result.getModel("RES");
   	           if (res == null) {
   	               // 查询订单为空
   	               logger.error("fail:orderId:" + bankOrder.getOrderId()+ " errcode:" + ProcCodeConstants.PROC_CODE_100E5062+ " err:bis query is null.");
   	               checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
   	               checkOrderResult.setErrMsg("银行返回对账结果为空");
   	           }
   	           // 如果查询成功，则一定有定单信息
   	           else {
   	        	   logger.error("平安EXPAY订单" + bankOrder.getOrderId() + "交易状态为"+ res.getStatus());
   	               // 成功处理
   	               if (PabConstants.EXPAY_QUERY_RESP_STATUS_SUCCESS.equals(res.getStatus())) {// 如果成功
   	                   logger.error("平安EXPAY订单" + bankOrder.getOrderId() + "交易状态为"+ PabConstants.EXPAY_QUERY_RESP_STATUS_SUCCESS + "，成功");
   	                   checkOrderResult.setSuccess(true);
   	                   InAccInfo accInfo = new InAccInfo();
   	                  // accInfo.setOrderId(res.getSerialNo()); // 为12位的银行订单号
   	                   accInfo.setOrderId(bankOrder.getOrderId());
   	                   accInfo.setAmount(new BigDecimal(res.getAmount()));
   	                   accInfo.setRetCode("00");
   	                   accInfo.setCardType(BankCardType.Unknown.toString());
   	                   checkOrderResult.setAccInfo(accInfo);
   	               }
   	               //处理中
   	               else if (PabConstants.EXPAY_QUERY_RESP_STATUS_UNKNOWN.equals(res.getStatus())) {// 如果处理中
   	                   logger.error("平安EXPAY订单" + bankOrder.getOrderId() + "交易状态为"+ PabConstants.EXPAY_QUERY_RESP_STATUS_UNKNOWN + "，处理中");
   	                   checkOrderResult.setErrMsg("银行返回处理中");
   	               }
   	               //失败处理
   	               else if (PabConstants.EXPAY_QUERY_RESP_STATUS_FAIL.equals(res.getStatus())) {// 如果失败
   	                   checkOrderResult.setBankFailure(true);
   	                   logger.error("平安EXPAY订单" + bankOrder.getOrderId() + "交易状态为"+ PabConstants.EXPAY_QUERY_RESP_STATUS_FAIL + "，失败");
   	                   checkOrderResult.setErrMsg("银行返回失败");
   	               }
   	           }
   			}
    	   

           return checkOrderResult;
           
       } catch (Exception e) {
           logger.error("bankClient fail.", e);
           checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
           checkOrderResult.setErrMsg("对账调用bis失败");
           return checkOrderResult;
       }
   }


   @Override
   public BankOrder getDbOrder() {
       // TODO Auto-generated method stub
       return null;
   }

   @Override
   public BaseMessage dayend(String bank_bus) {
       // TODO Auto-generated method stub
       return null;
   }

   @Override
   public Result getDayendMsg(String string) {
       // TODO Auto-generated method stub
       return null;
   }

   @Override
   public List<CheckOrderResult> checkDayend(String bank_bus) {
       // TODO Auto-generated method stub
       return null;
   }

   @Override
   public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
       // TODO Auto-generated method stub
       return null;
   }

}
